package com.huluobo.a2206douyindemo.mvvmdemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.huluobo.a2206douyindemo.R;
import com.huluobo.a2206douyindemo.databinding.ActivityLoginMvvmactivityBinding;
import com.huluobo.a2206douyindemo.mvpdemo.UserBean;

public class LoginMVVMActivity extends AppCompatActivity {

    //当在Gradle中打开ViewBinding的开关后,每个layout中的xml文件都会对应生成一个类,命名方式就是xml的名字后面加上binding
    //同事所有的xml中的控件都可以通过binding拿到
    ActivityLoginMvvmactivityBinding binding;
    LoginDemoViewModel viewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login_mvvmactivity);
        //ViewModel不能直接new,需要通过ViewModelProvider来拿到对应的class,通过反射的机制拿到的对应ViewModel
        viewModel = new ViewModelProvider(this).get(LoginDemoViewModel.class);
        binding.btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.login(
                        binding.username.getText().toString(),
                        binding.password.getText().toString()
                );
            }
        });

        viewModel.success.observe(this, new Observer<UserBean>() {
            @Override
            public void onChanged(UserBean userBean) {
                Toast.makeText(LoginMVVMActivity.this, "登录成功:" + userBean.getUsername(), Toast.LENGTH_SHORT).show();
            }
        });

        viewModel.failed.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Toast.makeText(LoginMVVMActivity.this, "登录失败:" + s, Toast.LENGTH_SHORT).show();
            }
        });
    }
}